package com.feng.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpUtil {
	public static final int MILLISECONDS_IN_SECOND = 1000;
	public static final String CACHE_CONTROL_HEADER = "Cache-Control";
	public static final String MAX_AGE_VALUE = "max-age=";
	public static final String PRE_CHECK_VALUE = "pre-check=";
	public static final String POST_CHECK_VALUE = "post-check=";
	public static final String LAST_MODIFIED_HEADER = "Last-Modified";
	public static final String EXPIRES_HEADER = "Expires";
	public static final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

	/**
	 * 为http请求设置Header
	 * @param response
	 * @param mCacheTime
	 */
	public void setHeader(HttpServletResponse response,Long mCacheTime) {
		//response.addHeader("expires", "28 Oct 2010 10:28:40 GMT");
		final long now = System.currentTimeMillis();
		response.addHeader(CACHE_CONTROL_HEADER,MAX_AGE_VALUE+mCacheTime.longValue());
		response.addHeader(CACHE_CONTROL_HEADER,PRE_CHECK_VALUE+mCacheTime.longValue());
		response.addHeader(CACHE_CONTROL_HEADER,POST_CHECK_VALUE+mCacheTime.longValue());
		response.addHeader(LAST_MODIFIED_HEADER, httpDateFormat.format(new Date(now)));
		System.out.println("CurrentTime:"+httpDateFormat.format(new Date(now)));
		response.addHeader(EXPIRES_HEADER, httpDateFormat.format(new Date(now +mCacheTime.longValue() * MILLISECONDS_IN_SECOND)));
		System.out.println("ExpiresTime:"+httpDateFormat.format(new Date(now +mCacheTime.longValue() * MILLISECONDS_IN_SECOND)));
	}
	public static byte[] file2b(String filepath) {
		ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
		try {
			File f = new File(filepath);
			FileInputStream stream = new FileInputStream(f);
			byte b[] = new byte[1000];
			int n;
			while ((n = stream.read(b)) != -1)
				out.write(b, 0, n);
			stream.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	public static Map getcookies(String input, String domain, String path) {
		Map cookies = new HashMap();
		if (!input.isEmpty()) {
			String cookie[] = input.split(";");
			for (int i = 0; i < cookie.length; i++)
				if (cookie[i].contains("=")) {
					Cookie c = new Cookie();
					String nameandvalue[] = cookie[i].split("=");
					c.setPath(path);
					c.setDomain(domain);
					c.setName(nameandvalue[0]);
					c.setValue(nameandvalue[1]);
					cookies.put(Integer.valueOf(i), c);
				} else {
					System.out.println("\u65E0\u6548\u7684cookie");
				}

		}
		return cookies;
	}

	public static Map getheaders(String input) {
		Map headers = new HashMap();
		if (!input.isEmpty()) {
			String header[] = input.split(";");
			for (int i = 0; i < header.length; i++)
				if (header[i].contains("=")) {
					String nameandvalue[] = header[i].split("=");
					Header h = new Header(nameandvalue[0], nameandvalue[1]);
					headers.put(Integer.valueOf(i), h);
				} else {
					System.out.println("\u65E0\u6548\u7684header");
				}

		}
		return headers;
	}

	public static Map get(String url, String cookie, String domain,
			String path, String header, boolean use_proxy) {
		Map cookies;
		Map headers;
		Map res;
		HttpClient client;
		GetMethod get;
		cookies = getcookies(cookie, domain, path);
		headers = getheaders(header);
		res = new HashMap();
		client = new HttpClient();
		if (use_proxy)
			client.getHostConfiguration().setProxy("10.99.20.30", 8080);
		get = new GetMethod(url);
		try {
			if (!cookies.isEmpty()) {
				for (int i = 0; i < cookies.size(); i++)
					client.getState().addCookie(
							(Cookie) cookies.get(Integer.valueOf(i)));

			}
			if (!headers.isEmpty()) {
				for (int i = 0; i < headers.size(); i++)
					get.addRequestHeader((Header) headers.get(Integer
							.valueOf(i)));
			}
			client.executeMethod(get);
			res.put("StatusCode", Integer.valueOf(get.getStatusCode()));
			res.put("ResponseBody", get.getResponseBodyAsString());
			Header resheaders[] = get.getResponseHeaders();
			res.put("resheaders", resheaders);
			Header reqheaders[] = get.getRequestHeaders();
			res.put("reqheaders", reqheaders);
			if (client.getState().getCookies().length > 0) {
				Cookie reqcookies[] = client.getState().getCookies();
				res.put("reqcookies", reqcookies);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return res;
	}

	public static Map post(String url, byte data[]) {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		Map result = new HashMap();
		try {
			if (data != null) {
				ByteArrayInputStream is = new ByteArrayInputStream(data);
				post.setRequestBody(is);
				int status = client.executeMethod(post);
				System.out.println((new StringBuilder("Http.Post.status "))
						.append(post.getStatusCode()).toString());
				result.put("status", Integer.valueOf(status));
				byte respbody[] = post.getResponseBody();
				result.put("data", respbody);
				is.close();
			} else {
				int status = client.executeMethod(post);
				System.out.println((new StringBuilder("Http.Post.status "))
						.append(post.getStatusCode()).toString());
				result.put("status", Integer.valueOf(status));
				byte respbody[] = post.getResponseBody();
				result.put("data", respbody);
			}
		} finally {
			post.releaseConnection();
			return result;
		}
	}
}
